package com.supermarket.seefood51.base

import android.content.Context
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup

import java.util.ArrayList

/**
 * Author: duke
 * DateTime: 2017-08-02 13:57
 * Description: recyclerView adapter的适配器包装类
 */
abstract class BaseRecyclerViewAdapter<T : RecyclerView.ViewHolder, D> @JvmOverloads constructor(val context: Context?, list: List<D>? = null) : RecyclerView.Adapter<T>() {
    val TAG = javaClass.simpleName
    private var mDataList: ArrayList<D> = ArrayList()
    private var onItemClickListener: OnItemClickListener<D>? = null
    private var onItemLongClickListener: OnItemLongClickListener<D>? = null



    fun setOnItemClickListener(l: OnItemClickListener<D>) {
        this.onItemClickListener = l
    }

    fun setOnItemLongClickListener(l: OnItemLongClickListener<D>) {
        this.onItemLongClickListener = l
    }

    init {
        if (this.context == null) {
            throw IllegalArgumentException("context is null")
        }
        setDatas(list)
    }

    fun clear() {
        mDataList?.clear()
        notifyDataSetChanged()
    }

    fun setDatas(data: List<D>?) {
        mDataList.clear()
        if (data != null) {
            mDataList.addAll(data)
        }
        notifyDataSetChanged()
    }

    fun addDatas(data: List<D>?) {
        if (data != null) {
            mDataList.addAll(data)
        }
        notifyDataSetChanged()
    }

    fun addDatas(position: Int, data: List<D>?) {
        if (data != null) {
            mDataList.addAll(position, data)
        }
        notifyDataSetChanged()
    }

    override fun getItemCount(): Int {
        return mDataList.size
    }

    fun getItem(position: Int): D? {
        return if (position < 0 || position >= mDataList.size) {
            null
        } else mDataList[position]
    }

    fun newView(layoutId: Int, viewGroup: ViewGroup?): View? {
        return if (viewGroup == null) {
            null
        } else LayoutInflater.from(viewGroup.context).inflate(layoutId, viewGroup, false)
    }

    fun invokeOnClickEvent(view: View?, position: Int) {
        if (view == null || onItemClickListener == null) {
            return
        }
        view.setOnClickListener { onItemClickListener!!.onClick(view, getItem(position), position) }
    }

    fun invokeOnLongClickEvent(view: View?, position: Int) {
        if (view == null || onItemLongClickListener == null) {
            return
        }
        view.setOnLongClickListener {
            onItemLongClickListener!!.onLongClick(view, getItem(position), position)
            true
        }
    }

    interface OnItemClickListener<M> {
        fun onClick(view: View?, data: M?, position: Int)
    }

    interface OnItemLongClickListener<M> {
        fun onLongClick(view: View?, data: M?, position: Int)
    }

}
